package classLoader;

import java.io.*;

/**
 * @program: minicat
 * @description
 * @author: luffy
 * @create: 2020-08-06 00:10
 */
public class MyClassLoader extends ClassLoader {

    private String path;

    public MyClassLoader(String path) {
        super();
        this.path = path;
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        return super.loadClass(name, resolve);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] result = getMyClass(name);
            if (result == null) {
                throw new FileNotFoundException(name);
            }else {
                return defineClass(name, result, 0, result.length);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new ClassNotFoundException(name);
    }

    private byte[] getMyClass(String name) {
        InputStream in = null;
        ByteArrayOutputStream out = null;
        //Users/suyafei/Desktop/zuoye/Demo.class
        path = path + name + ".class";

        try {
            in = new FileInputStream(path);
            out = new ByteArrayOutputStream();

            byte[] buffer = new byte[2048];

            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            return out.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                in.close();
                out.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

}
